﻿using System;
using System.ComponentModel;

namespace Present.Commands.Tests
{
    /// <summary>
    /// Useful for testing and Classes that want to transparently swap between Synch and Asynch behaviour
    /// </summary>
    public class SynchronousBackgroundWorker : Component, IBackgroundWorker
    {

        public event DoWorkEventHandler DoWork;
        
        #pragma warning disable 67
        public event ProgressChangedEventHandler ProgressChanged;

        public event RunWorkerCompletedEventHandler RunWorkerCompleted;

        public void RunWorkerAsync()
        {
            RunWorkerAsync(null);
        }

        public void RunWorkerAsync(object argument)
        {
            try
            {
                IsBusy = true;
                Exception workException = null;
                DoWorkEventArgs doWorkEventArgs = new DoWorkEventArgs(argument);
                try
                {
                    if (DoWork != null)
                        DoWork(this, doWorkEventArgs);
                }
                catch (Exception e)
                {
                    workException = e;
                }


                if (RunWorkerCompleted != null)
                {
                    RunWorkerCompleted(this,
                                       new RunWorkerCompletedEventArgs(doWorkEventArgs.Result, workException, false));
                }
            }
            finally
            {
                IsBusy = false;
            }
        }


        public bool CancellationPending { get; private set; }

        public bool IsBusy { get; private set; }

        public bool WorkerReportsProgress { get; set; }

        public bool WorkerSupportsCancellation { get; set; }

        public void CancelAsync()
        {
            CancellationPending = true;
        }

        public void ReportProgress(int percentProgress)
        {
            //Not Implemented for Synch
        }

        public void ReportProgress(int percentProgress, object userState)
        {
            //Not Implemented for Synch
        }

       
    }
}